import { useLocation } from "react-router-dom";
import { Form, Select, Input, Button, Checkbox, Popover, Row, Col, Space, message, Alert, Modal } from "antd";
import SubTitle from "@/views/components/SubTitle";
import Typography from "@/views/components/Typography";
import { QuestionCircleOutlined } from "@ant-design/icons";
import { useScanRegistrationStore } from "../../store";
import { confirmReceipt, agreeWithRefund, confirmReceive } from "../../service";
import { fieldMap } from "../../fieldMap";
import useUserStore from "@/stores/user.js";
import ExpressSelect from "./ExpressSelect";
import TaobaoCode from "@/pages/OrderModule/salesOrder/components/TaobaoCode";
import { useEffect, useState } from "react";
// import usePrint from "@/views/hooks/usePrint";
import { usePrintLabel } from "@/views/hooks/usePrintLabel";
import CreateAfterSales from "../../../salesOrder/components/CreateAfterSales";
import { printKmUniqcode } from '@/utils/printKm.js';
import { ExclamationCircleOutlined } from '@ant-design/icons';

const { confirm } = Modal;

const Question = () => {
	return (
		<Popover
			content={
				<div style={{ width: "186px" }}>
					注：
					<br />
					针对平台售后单中已发货仅退款、退货退款的状态下的订单，符合以上条件后，操作确认收货时，同时进行退款操作
				</div>
			}
		>
			<Typography color="#B1B7C3">
				<QuestionCircleOutlined />
			</Typography>
		</Popover>
	);
};

const Filter = () => {
	const location = useLocation();
	const { orderList, orderIdParameter, updateState, isConfirmReceivingGoods, updateAfterSalesIds } = useScanRegistrationStore();
	const [visible, setVisible] = useState("");
	const [isConfirmRetureAmount, setIsConfirmRetureAmount] = useState(false);
	const userInfo = useUserStore(state => state.userInfo);
	const printOptions = [];

	const {
		printUniqueCode,
		initPrint,
		template,
		printData,
		printerList,
		labelPrinter,
		getPrintDataFunc,
		configObj,
		printAction,
		printSuccess,
		getExpressRelativePrinter,
		setLabelRelativePrinter
	} = usePrintLabel({ printType: "ReturnGoods", printName: "售后单" });
	const [form] = Form.useForm();

	useEffect(() => {
		let index = 0;
		const newData = [];
		orderList.forEach(orderItem => {
			const goodsList = orderItem[fieldMap["售后商品列表"]] || [];
			goodsList.forEach(goodItem => {
				goodItem.returnDestination == 2
					? goodItem[fieldMap["商品唯一码"]].forEach(codeItem => {
							newData.push({
								uniqueCode: codeItem.value, //"条形码",
								codeSN: ++index, // "序号",
								skuCode: goodItem[fieldMap["供应商商品编码"]] || goodItem[fieldMap["系统商品编码"]], //"商品编码",
								skuName: goodItem[fieldMap["供应商商品名称"]] || goodItem[fieldMap["系统商品名称"]], //"商品名称",
								supplierName: goodItem[fieldMap["供应商"]] //"供应商名称",
							});
						})
					: newData.push({
							uniqueCode: goodItem.sysSkuCode, //"条形码",
							codeSN: ++index, // "序号",
							skuName: goodItem[fieldMap["供应商商品名称"]] || goodItem[fieldMap["系统商品名称"]], //"商品名称",
							supplierName: goodItem[fieldMap["供应商"]] //"供应商名称",
						});
			});
		});
		const obj = getExpressRelativePrinter() || {};
		form.setFieldsValue({
			printer: obj["售后单"]
		});
		form.setFieldValue("售后单", obj["售后单"]);
		console.log(configObj, newData, "configObj");
		initPrint(newData);
	}, [configObj, orderList]);

	const ReturnReasonGroup = props => {
		return (
			<Form.Item name="condition">
				<Checkbox.Group>
					<Row>
						{[
							{ value: 0, label: "商品无误" },
							{ value: 1, label: "存在次品" },
							{ value: 2, label: "商品多收" },
							{ value: 3, label: "部分收货" }
						].map(item => {
							return (
								<Col key={item.value} span={12}>
									<Checkbox value={item.value}>{item.label}</Checkbox>
								</Col>
							);
						})}
					</Row>
				</Checkbox.Group>
			</Form.Item>
		);
	};

	const onFinish = async values => {
		if(!orderList.length > 0) {
			return;
		}
		if (!values["售后单"]) {
			message.info("请选择打印机");
			return;
		}
		const ids = orderList.map(item => item[fieldMap["售后id"]]);
		// 判断当登记的拆包数量≠申请退货数量（小于或大于）
		const unpackNumStatus = orderList?.map(i => {
			return i?.goodsList?.some(s => {
				return Number(s?.unpackNum) !== Number(s?.goodsNum ?? 0)
			})
		})?.some(i => i)
		// 当登记的货品种类＜确认收货时的货品种类（多退场景，例：申请A，结果退了A和B
		const takeGoodsStatus = orderList?.map(i => {
			return i?.goodsList?.filter(f => !f?.isNewGoods)?.length === i?.goodsList?.length ? false : true
		})?.some(i => i)
		if (unpackNumStatus || takeGoodsStatus) {
			confirm({
				title: '',
				icon: <ExclamationCircleOutlined />,
				content: '退回包裹中存在拆包数量与申请数量不一致的商品是否完成退货',
				okText: '是',
				cancelText: '否',
				async onOk() {
					if (values.isConfirmRetureAmount) {
						if (!ids?.length) {
							setVisible("unInfoClaim");
							return;
						}
						if(values.condition && values.condition.length) { //勾选售后包裹状态满足以下条件可自动退款再退款
								START_LOADING();
								await agreeWithRefund({
										ids,
										...values
								});
								END_LOADING();
						}
						confirmReceiptFn();
						// await handleAgreeWithRefund(values);
						return;
					}
					// 无信息件绑定
					if (values.isEmptyInfoOrder && !ids?.length) {
						setVisible("unInfoClaim");
						return;
					}
					confirmReceiptFn();
				},
				onCancel() {
					console.log('Cancel');
				},
			});
		} else {
			// 确认收货后自动退款
			if (values.isConfirmRetureAmount) {
				if (!ids?.length) {
					setVisible("unInfoClaim");
					return;
				}
				if(values.condition && values.condition.length) { //勾选售后包裹状态满足以下条件可自动退款再退款
						START_LOADING();
						await agreeWithRefund({
								ids,
								...values
						});
						END_LOADING();
				}
				confirmReceiptFn();
				// await handleAgreeWithRefund(values);
				return;
			}
			// 无信息件绑定
			if (values.isEmptyInfoOrder && !ids?.length) {
				setVisible("unInfoClaim");
				return;
			}
			confirmReceiptFn();
		}
	};

	async function confirmReceiptFn(newOrderList) {
		let values = form.getFieldsValue();
		let condition = ["0", "0", "0", "0"];

		//收货确认换货单调用
		if(values.isAutoExchangeOrder) {
			const ids = orderList.map(v => v.afterSaleId);
			confirmReceive({
				ids
			})
		}
		if (values.isConfirmRetureAmount && values.condition) {
			values.condition.forEach(index => {
				condition[index] = 1;
			});
		}

		let isDefectiveGoods = false;
		const params = (newOrderList || orderList).map(item => {
			const goodsDTOList = item[fieldMap["售后商品列表"]].map(goodsItem => {
				const normalUniqueCodes = goodsItem[fieldMap["商品唯一码"]]
					.filter(child => child.status === 1 && child.selected)
					.map(item => item.value);
				const defectiveUniqueCodes = goodsItem[fieldMap["商品唯一码"]]
					.filter(child => child.status === 2 && child.selected)
					.map(item => item.value);

				if (defectiveUniqueCodes.length > 0) {
					isDefectiveGoods = true;
				}
				return {
					defectiveUniqueCodes: defectiveUniqueCodes,
					normalUniqueCodes: normalUniqueCodes,
					unpackingNum: Number(goodsItem[fieldMap["拆包数量"]] || 0),
					storeId: goodsItem[fieldMap["供应商id"]],
					storeName: goodsItem[fieldMap["供应商"]],

					goodsId: goodsItem[fieldMap["供应商商品id"]],
					goodsImage: goodsItem[fieldMap["供应商商品图片"]],
					goodsName: goodsItem[fieldMap["供应商商品名称"]],
					goodsSpec: goodsItem[fieldMap["供应商颜色规格"]],
					skuCode: goodsItem[fieldMap["供应商商品编码"]],
					skuId: goodsItem[fieldMap["供应商商品编码id"]],
					spuCode: goodsItem[fieldMap["供应商款式编码"]],

					sysGoodsId: goodsItem[fieldMap["系统商品id"]],
					sysGoodsImage: goodsItem[fieldMap["系统商品图片"]],
					sysGoodsName: goodsItem[fieldMap["系统商品名称"]],
					sysGoodsSpec: goodsItem[fieldMap["系统颜色规格"]],
					sysPrice: goodsItem[fieldMap["系统商品单价"]] || 0,
					sysSkuCode: goodsItem[fieldMap["系统商品编码"]],
					sysSpuCode: goodsItem[fieldMap["系统款式编码"]],

					afterSaleGoodsId: goodsItem[fieldMap["售后商品id"]],
					defectiveNum: defectiveUniqueCodes.length,
					uuid: goodsItem["用户id"],
					isAdd: goodsItem[fieldMap["是否是新增商品"]] ? true : false,
				};
			});

			return {
				// 用于创建售后单的参数
				createAfterSaleOrder: orderList,
				isAutoExchangeOrder: values.isAutoExchangeOrder ? 1 : 0,
				remark: item[fieldMap["退货备注"]],
				salesAfterOrderId: item[fieldMap["售后id"]],
				salesAfterOrderNo: item[fieldMap["售后单号"]],
				salesAfterType: item[fieldMap["售后类型"]],
				shopName: item[fieldMap["店铺名称"]],
				orderNo: item[fieldMap["内部系统订单号"]][0],
				uuid: String(userInfo.uuid),
				goodsDTOList: goodsDTOList,
				isConfirm: true,
				orderId: orderIdParameter,
			};
		});
		try {
			START_LOADING();
			const res = await confirmReceipt(params);
			END_LOADING();
			if(res.success && res.data) {
				printKmUniqcode(JSON.parse(res.data), values["售后单"], () => {
					//打印任务推送完成回调
				});
			}
			updateState({
				isConfirmReceivingGoods: true,
				isDefectiveGoods
			});
		} catch (error) {
			console.log(error);
		}
	}

	async function handleAgreeWithRefund(params = {}) {
		const ids = orderList.map(item => item[fieldMap["售后id"]]);
		agreeWithRefund({
			ids,
			...params
		});

		// if (res.data[0]?.gatewayOperateVO?.errorCode === 2001) {
		// 	setVisible("toabao");
		// 	return;
		// }

		confirmReceiptFn();
	}

	const options =
		Array.isArray(printerList) &&
		printerList.map(d => (
			<Option key={d} value={d}>
				{d}
			</Option>
		));

	const CreateAfterSalesModalProps = {
		item: orderList[0]?.[fieldMap["售后商品列表"]] || [],
		scene: "unInfoClaim",
		handleOk: async () => {
			console.log("确认收货");
			const orderList = await updateAfterSalesIds();

			confirmReceiptFn(orderList);
		},
		handleCancel: () => {
			setVisible("");
		}
	};

	return (
		<>
			{visible == "taobao" && <TaobaoCode handleOk={code => handleAgreeWithRefund({})} />}
			{visible == "unInfoClaim" && <CreateAfterSales {...CreateAfterSalesModalProps} />}

			<Form
				form={form}
				wrapperCol={{ span: 24 }}
				size="large"
				onFinish={onFinish}
				onValuesChange={value => {
					if (value.isConfirmRetureAmount !== undefined) {
						setIsConfirmRetureAmount(value.isConfirmRetureAmount);
					}
				}}
				initialValues={{
					isAutoExchangeOrder: true,
					condition: [0]
				}}
				disabled={isConfirmReceivingGoods}
			>
				<section>
					<SubTitle symbol as="s3" title="售后信息" />
					<div style={{ marginLeft: 8 }}>
						<p style={{ marginTop: 16 }}>
							<Typography color="#666">快递单号：</Typography>
							<Typography color="#333">{location.state?.expressSn || (orderList[0] || {}).refundLogisticsNo}</Typography>
						</p>
						<p style={{ marginTop: 12 }}>
							<Typography color="#666">快递公司：</Typography>
							<Typography color="#333">{location.state?.expressName || (orderList[0] || {}).refundLogisticsCompany}</Typography>
						</p>
						{/* <Form.Item
              className='form-item-bg'
              name="orderNo1"
              label={<Typography color="#666">快递公司：</Typography> }
              colon={false}
              labelCol={3}
              style={{marginTop: 16}}
            >
              <ExpressSelect placeholder="快递公司" />
            </Form.Item> */}
					</div>
				</section>

				<section style={{ marginTop: 24 }}>
					<SubTitle symbol as="s3" title="便捷操作" />

					<Form.Item name="售后单" style={{ marginTop: 16 }}>
						<Select placeholder="请选择打印机" onChange={name => setLabelRelativePrinter(name)} value={configObj["快销退货条码"]}>
							{options}
						</Select>
					</Form.Item>

					{/* 默认勾选这个 */}
					<Form.Item name="isAutoExchangeOrder" valuePropName="checked" style={{ marginBottom: 0 }}>
						<Checkbox>收货确认换货单</Checkbox>
					</Form.Item>
					<Form.Item name="isEmptyInfoOrder" valuePropName="checked" style={{ marginBottom: 0 }}>
						<Checkbox>无信息件确认收货后绑定订单</Checkbox>
					</Form.Item>
					<Form.Item name="isConfirmRetureAmount" valuePropName="checked" style={{ marginBottom: 0 }}>
						<Checkbox>确认收货后自动退款</Checkbox>
					</Form.Item>

					{isConfirmRetureAmount && (
						<>
							<div style={{ margin: "16px 0" }}>
								<Typography>
									售后包裹状态满足以下条件可自动退款 <Question />
								</Typography>
							</div>
							<ReturnReasonGroup />
						</>
					)}

					<Form.Item style={{ marginBottom: 0 }}>
						<Button type="primary" htmlType="submit" >
							确认收货
						</Button>
					</Form.Item>
                    <Alert style={{marginTop: 16}} message={<Typography as="s1"><Typography type="error" as="s1">注</Typography>：当扫描快递单号与发货单号一致时，并且没有售后单时，确认收货后则自动进行快递登记并绑定对应发货系统单号生成售后单</Typography>} />
				</section>
			</Form>
		</>
	);
};

export default Filter;
